﻿using System;
using System.Windows.Forms;
using YougeBookmark.Services;
using YougeBookmark.Utilities;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using YougeBookmark.Models;

namespace YougeBookmark.UI
{
    public partial class TagForm : Form
    {
        private readonly TagManager _tagManager;
        private readonly Logger _logger;
        private Label label1;
        private Tag _selectedTag;

        public List<string> SelectedTags { get; private set; } = new List<string>();

        public TagForm(TagManager tagManager, Logger logger)
        {
            _tagManager = tagManager;
            _logger = logger;
            InitializeComponent();
            InitializeGrid();
            LoadTags();
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TagForm));
            dgvTags = new DataGridView();
            txtTagName = new TextBox();
            btnAdd = new Button();
            btnSave = new Button();
            btnDelete = new Button();
            btnConfirm = new Button();
            label1 = new Label();
            ((System.ComponentModel.ISupportInitialize)dgvTags).BeginInit();
            SuspendLayout();
            // 
            // dgvTags
            // 
            dgvTags.Location = new Point(12, 12);
            dgvTags.Name = "dgvTags";
            dgvTags.Size = new Size(400, 300);
            dgvTags.TabIndex = 1;
            dgvTags.SelectionChanged += DgvTags_SelectionChanged;
            // 
            // txtTagName
            // 
            txtTagName.Location = new Point(12, 345);
            txtTagName.Name = "txtTagName";
            txtTagName.Size = new Size(200, 23);
            txtTagName.TabIndex = 2;
            // 
            // btnAdd
            // 
            btnAdd.Location = new Point(220, 318);
            btnAdd.Name = "btnAdd";
            btnAdd.Size = new Size(75, 23);
            btnAdd.TabIndex = 3;
            btnAdd.Text = "新增";
            btnAdd.Click += BtnAdd_Click;
            // 
            // btnSave
            // 
            btnSave.Location = new Point(301, 319);
            btnSave.Name = "btnSave";
            btnSave.Size = new Size(75, 23);
            btnSave.TabIndex = 4;
            btnSave.Text = "保存";
            btnSave.Click += BtnSave_Click;
            // 
            // btnDelete
            // 
            btnDelete.Location = new Point(220, 347);
            btnDelete.Name = "btnDelete";
            btnDelete.Size = new Size(73, 23);
            btnDelete.TabIndex = 5;
            btnDelete.Text = "删除";
            btnDelete.Click += BtnDelete_Click;
            // 
            // btnConfirm
            // 
            btnConfirm.Location = new Point(301, 347);
            btnConfirm.Name = "btnConfirm";
            btnConfirm.Size = new Size(75, 23);
            btnConfirm.TabIndex = 0;
            btnConfirm.Text = "确认";
            btnConfirm.Click += btnConfirm_Click;
            // 
            // label1
            // 
            label1.AutoSize = true;
            label1.Location = new Point(15, 323);
            label1.Name = "label1";
            label1.Size = new Size(71, 17);
            label1.TabIndex = 6;
            label1.Text = "标签项名称:";
            // 
            // TagForm
            // 
            ClientSize = new Size(423, 377);
            Controls.Add(label1);
            Controls.Add(btnConfirm);
            Controls.Add(dgvTags);
            Controls.Add(txtTagName);
            Controls.Add(btnAdd);
            Controls.Add(btnSave);
            Controls.Add(btnDelete);
            Icon = (Icon)resources.GetObject("$this.Icon");
            Name = "TagForm";
            StartPosition = FormStartPosition.CenterParent;
            Text = "标签管理";
            ((System.ComponentModel.ISupportInitialize)dgvTags).EndInit();
            ResumeLayout(false);
            PerformLayout();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        // 新增确认按钮声明
        private Button btnConfirm;

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.OK)
            {
                // 获取所有选中的标签名称
                SelectedTags = dgvTags.SelectedRows
                    .Cast<DataGridViewRow>()
                    .Select(row => row.Cells["Name"].Value.ToString())
                    .ToList();
            }
            base.OnFormClosing(e);
        }

        private void InitializeGrid()
        {
            dgvTags.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvTags.MultiSelect = true; // 启用多选

            dgvTags.AutoGenerateColumns = false;
            dgvTags.Columns.Clear();

            // 标签名称列
            dgvTags.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "Name",  // 显式设置列标识
                HeaderText = "标签名称",
                DataPropertyName = "Name",
                Width = 200
            });

            // 使用次数列
            dgvTags.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "UsageCount",
                HeaderText = "使用次数",
                DataPropertyName = "UsageCount",
                Width = 100
            });
        }

        private async void LoadTags()
        {
            try
            {
                var (tags, _) = await _tagManager.GetPagedTagsAsync(0, int.MaxValue);
                dgvTags.DataSource = tags.Select(t => new
                {
                    t.Tag.Id,
                    t.Tag.Name,
                    /*UsageCount = */
                    t./*BookmarkTags*/UsageCount
                }).ToList();
            }
            catch (Exception ex)
            {
                _logger.Error($"加载标签失败: {ex.Message}", ex);
                MessageBox.Show("加载标签数据失败");
            }
        }

        private async void BtnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtTagName.Text))
            {
                MessageBox.Show("请输入标签名称");
                return;
            }

            try
            {
                var newTag = await _tagManager.CreateTagAsync(txtTagName.Text.Trim());
                if (newTag != null)
                {
                    txtTagName.Clear();
                    LoadTags();
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"创建标签失败: {ex.Message}", ex);
                MessageBox.Show("创建标签失败: " + ex.Message);
            }
        }

        private async void BtnSave_Click(object sender, EventArgs e)
        {
            if (_selectedTag == null) return;

            try
            {
                var updated = await _tagManager.UpdateTagAsync(
                    _selectedTag.Id,
                    txtTagName.Text.Trim()
                );

                if (updated != null)
                {
                    LoadTags();
                    txtTagName.Clear();
                    _selectedTag = null;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"更新标签失败: {ex.Message}", ex);
                MessageBox.Show("更新失败: " + ex.Message);
            }
        }

        private async void BtnDelete_Click(object sender, EventArgs e)
        {
            if (_selectedTag == null) return;

            if (MessageBox.Show(
                $"确定要删除标签 '{_selectedTag.Name}' 吗？关联书签将解除关联",
                "确认删除",
                MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            try
            {
                if (await _tagManager.DeleteTagAsync(_selectedTag.Id))
                {
                    LoadTags();
                    txtTagName.Clear();
                    _selectedTag = null;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"删除标签失败: {ex.Message}", ex);
                MessageBox.Show("删除失败: " + ex.Message);
            }
        }

        private void DgvTags_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvTags.SelectedRows.Count == 0) return;

            var selected = dgvTags.SelectedRows[0].DataBoundItem as dynamic;
            _selectedTag = new Tag
            {
                Id = selected.Id,
                Name = selected.Name
            };
            txtTagName.Text = selected.Name;
        }

        // 控件声明
        private DataGridView dgvTags;
        private TextBox txtTagName;
        private Button btnAdd;
        private Button btnSave;
        private Button btnDelete;
    }
}